<template>
  <el-card>
    <template #header>
      <div class="flex">
        <div class="flex1">生态任务分类</div>
      </div>
    </template>
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="80px"
      class="page"
    >
      <el-form-item label="用户姓名" prop="realName">
        <el-input v-model="formData.realName" />
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formData.phone" maxlength="11"></el-input>
      </el-form-item>

      <el-form-item label="是否可用" prop="status">
        <c-radio v-model="formData.status" constKey="status"></c-radio>
      </el-form-item>
    </el-form>

    <div>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">
        提交
      </el-button>
      <el-button @click="$router.back()">取消 </el-button>
    </div>
  </el-card>
</template>
<script lang="ts" setup>
import API from '@/api/api';
import { useMessage } from '@/hooks/useMessage';
import { createRequireRole } from '@/utils/rules';
import { useRequest } from 'vue-hooks-plus';
const route = useRoute();
const router = useRouter();
const message = useMessage(); // 消息弹窗
const isNew = !route.query.id;
useRequest(
  async () => {
    return API.sysUserController.getinfo({
      userId: route.query.id,
    });
  },
  {
    ready: !!route.query.id,
    onSuccess(res: any) {
      formData.value = res;
    },
  }
);

const submitReq = useRequest(
  async (sendData: any) => {
    if (isNew) {
      return API.sysUserController.add(sendData);
    }
    return API.sysUserController.update({
      userId: route.query.id,
      ...sendData,
    });
  },
  {
    manual: true,
  }
);

const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const formData = ref({});
const formRules = reactive({
  countryName: [createRequireRole()],
  organizationId: [createRequireRole()],
  realName: [createRequireRole()],
  phone: [
    createRequireRole(),
    {
      min: 11,
      max: 11,
      trigger: 'blur',
      message: '手机号应为11位',
    },
    { pattern: /^1\d{10}$/, message: '手机号格式不正确', trigger: 'blur' },
  ],
  sex: [createRequireRole()],
  status: [createRequireRole()],
});
const formRef = ref(); // 表单 Ref

const submitForm = async () => {
  // 校验表单
  if (!formRef) return;
  const valid = await formRef.value.validate();
  if (!valid) return;
  // 提交请求
  formLoading.value = true;

  const data = formData.value;
  await submitReq.runAsync(data);
  if (isNew) {
    message.success('新增成功');
  } else {
    message.success('更新成功');
  }
  router.back();
};

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    category: '',
    name: '',
    key: '',
    value: '',
    visible: true,
    remark: '',
  };
  formRef.value?.resetFields();
};
</script>
